package comment

import (
	"context"
	"gitee.com/enjoy_5/comment-rpc/internal/server"
	"gitee.com/enjoy_5/comment-rpc/proto/comment"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type CommentServerApi struct {
	comment.UnimplementedCommentServer
}

// 评论类型判断
func CommentTypeJudgment(c *comment.CommentInfo) error {
	switch c.ObjectType {
	case comment.TYPE_GOODS:
		if c.Rating == 0 {
			return status.Errorf(codes.InvalidArgument, "请给商品评分")
		}
		if len([]rune(c.Text)) > 200 {
			return status.Errorf(codes.InvalidArgument, "商品评论内容请在200字以内")
		}
	case comment.TYPE_ESSAY:
		if c.Text == "" {
			return status.Errorf(codes.InvalidArgument, "文章内容不能为空")
		}
	default:
		return status.Errorf(codes.InvalidArgument, "未知类型")
	}
	return nil
}

func (c *CommentServerApi) AddComment(_ context.Context, in *comment.CreateCommentReq) (*comment.CreateCommentResp, error) {
	switch in.Comment.Pid {
	case 0:
		if err := CommentTypeJudgment(in.Comment); err != nil {
			return nil, err
		}
	}

	createComment, err := server.CreateComment(in.Comment)
	if err != nil {
		return nil, err
	}

	return &comment.CreateCommentResp{Comment: createComment}, nil
}

func (c *CommentServerApi) DelComment(_ context.Context, in *comment.DelCommentReq) (*comment.DelCommentResp, error) {
	err := server.DelComment(int(in.CommentId))
	if err != nil {
		return nil, err
	}

	return &comment.DelCommentResp{}, nil
}

func (c *CommentServerApi) GetCommentList(_ context.Context, in *comment.GetListReq) (info *comment.GetListResp, err error) {
	if in.Size == 0 {
		in.Size = 5
	}
	if in.Page == 0 {
		in.Page = 1
	}
	list, err := server.GetCommentList(in)
	if err != nil {
		return nil, err
	}

	return &comment.GetListResp{Comment: list}, nil
}

func (c *CommentServerApi) UpdateLike(_ context.Context, in *comment.UpdateLikeReq) (*comment.UpdateLikeResp, error) {
	err := server.UpdateLike(in.Like)
	if err != nil {
		return nil, err
	}
	return &comment.UpdateLikeResp{}, nil
}

func (c *CommentServerApi) GetCNumByRat(_ context.Context, in *comment.GetCNumByRatReq) (info *comment.GetCNumByRatResp, err error) {
	rat, err := server.GetCNumByRat(in)
	if err != nil {
		return nil, err
	}

	return &comment.GetCNumByRatResp{Num: rat.Num}, nil
}
